import React, { useState, useEffect, useContext } from "react";
import {
  View,
  Text,
  StyleSheet,
  TextInput,
  ScrollView,
  TouchableOpacity,
  Keyboard,
  Modal,
  TouchableWithoutFeedback,
  Image,
  Alert,
} from "react-native";
import { AntDesign } from "@expo/vector-icons";
import * as ImagePicker from "expo-image-picker";
import ArticleContext from "../../context/preparation/ArticleContext";
import LoadingBar from "../../components/InterView/LoadingBar";

const AddArticle = ({ navigation }) => {
  const [title, setTitle] = useState(null); //标题
  const [isVisible, setIsVisible] = useState(false); //添加图片弹框
  const [keyboardIsOpen, setKeyboardIsOpen] = useState(false); //键盘
  const [imageList, setImageList] = useState([]);
  const [contents, setContents] = useState([
    { type: 0, content: "" }, //0 副标题
    { type: 1, content: "" }, //1 段落   ,2 图片
  ]);

  const { addArtical, isArticleLoading } = useContext(ArticleContext);

  useEffect(() => {
    Keyboard.addListener("keyboardDidShow", _keyboardDidShow);
    Keyboard.addListener("keyboardDidHide", _keyboardDidHide);

    // cleanup function
    return () => {
      Keyboard.removeAllListeners("keyboardDidShow");
      Keyboard.removeAllListeners("keyboardDidHide");
    };
  }, []);

  const _keyboardDidShow = () => {
    setKeyboardIsOpen(true);
  };

  const _keyboardDidHide = () => {
    setKeyboardIsOpen(false);
  };

  const deleteOption = (index) => {
    setContents((preContents) => {
      return preContents.filter((t_item, t_index) => index !== t_index);
    });
  };

  const deleteImage = (index, picture) => {
    setContents((preContents) => {
      return preContents.filter((t_item, t_index) => index !== t_index);
    });
    setImageList((preImages) => {
      return preImages.filter((t_item) => t_item.uri !== picture.uri);
    });
  };

  const pickImage = async () => {
    // No permissions request is necessary for launching the image library
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      allowsEditing: true,
      // aspect: [1, 1],
      quality: 1,
    });
    if (!result.cancelled) {
      setImageList([...imageList, result]);
      setContents([...contents, { type: 2, content: result }]);
      setIsVisible(false);
    }
    // console.log(result);
  };

  const openCamera = async () => {
    const permissionResult = await ImagePicker.requestCameraPermissionsAsync();
    if (permissionResult.granted === false) {
      alert("您拒绝该应用使用您的相机");
      return;
    }
    const result = await ImagePicker.launchCameraAsync({
      allowsEditing: true,
      quality: 1,
      // aspect: [4, 3],
    });
    if (!result.cancelled) {
      setImageList([...imageList, result]);
      setContents([...contents, { type: 2, content: result }]);
      setIsVisible(false);
    }
    // console.log(result);
  };

  const onConfirm = () => {
    Alert.alert("提示", "确定要提交吗?", [
      {
        text: "取消",
        style: "cancel",
      },
      {
        text: "确定",
        onPress: async () => {
          let now = new Date();
          let mytime =
            now.getFullYear() +
            "-" +
            (now.getMonth() + 1) +
            "-" +
            now.getDate();
          let article = {
            title: title,
            contents: contents,
            imageList: imageList,
            time: mytime,
            type: 0, //普通文章
          };
          addArtical(article, () => {
            navigation.navigate("ArticleManage");
          });
        },
      },
    ]);
    // navigation.navigate("ArticlePreview", { article: article });
  };

  const onPreview = () => {
    let now = new Date();
    let mytime =
      now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate();
    let article = {
      title: title,
      contents: contents,
      imageList: imageList,
      time: mytime,
    };
    navigation.navigate("ArticlePreview", {
      article: article,
    });
  };

  return (
    <View style={styles.container}>
      <LoadingBar visible={isArticleLoading} />
      <ScrollView style={{ flex: 1 }}>
        <View>
          <View style={styles.top}>
            <View style={styles.title}>
              <Text style={styles.titleIcon}>* </Text>
              <Text style={styles.titleText}>标题</Text>
            </View>
            <TextInput
              style={styles.inputBox}
              multiline={true}
              value={title}
              placeholder="请输入文章标题"
              onChangeText={(text) => {
                setTitle(text);
              }}
            />
          </View>
          <View style={styles.context}>
            <View style={styles.title}>
              <Text style={styles.titleIcon}>* </Text>
              <Text style={styles.titleText}>正文</Text>
            </View>

            {contents.map((item, index) => {
              if (item.type === 0) {
                return (
                  <View style={styles.deleteOption} key={index}>
                    <TouchableOpacity
                      style={{ marginRight: 10 }}
                      onPress={() => deleteOption(index)}
                    >
                      <AntDesign name="minuscircle" size={18} color="red" />
                    </TouchableOpacity>
                    <View style={{ flex: 1 }}>
                      <TextInput
                        style={[styles.inputLine, { padding: 5 }]}
                        multiline={true}
                        value={item.content}
                        placeholder="请输入文章副标题"
                        onChangeText={(text) => {
                          let item = { type: 0, content: text };
                          setContents((preContents) => {
                            return preContents.map((t_item, t_index) => {
                              return index === t_index ? item : t_item;
                            });
                          });
                        }}
                      />
                    </View>
                  </View>
                );
              } else if (item.type == 1) {
                return (
                  <View style={styles.deleteOption} key={index}>
                    <TouchableOpacity
                      style={{ marginRight: 10 }}
                      onPress={() => deleteOption(index)}
                    >
                      <AntDesign name="minuscircle" size={18} color="red" />
                    </TouchableOpacity>
                    <View style={{ flex: 1 }}>
                      <TextInput
                        style={[
                          styles.inputBox,
                          { padding: 20, paddingLeft: 10 },
                        ]}
                        multiline={true}
                        value={item.content}
                        placeholder="请输入段落内容"
                        onChangeText={(text) => {
                          let item = { type: 1, content: text };
                          setContents((preContents) => {
                            return preContents.map((t_item, t_index) => {
                              return index === t_index ? item : t_item;
                            });
                          });
                        }}
                      />
                    </View>
                  </View>
                );
              } else {
                return (
                  <View key={index} style={styles.deleteOption}>
                    <TouchableOpacity
                      style={{ marginRight: 10 }}
                      onPress={() => deleteImage(index, item.content)}
                    >
                      <AntDesign name="minuscircle" size={18} color="red" />
                    </TouchableOpacity>
                    <View
                      style={{
                        flex: 1,
                        borderColor: "#ddd",
                        borderWidth: 1,
                        borderRadius: 2,
                        justifyContent: "center",
                        alignItems: "center",
                      }}
                    >
                      <Image
                        source={{ uri: item.content.uri }}
                        style={{
                          width: 250,
                          height: 250,
                          resizeMode: "contain",
                        }}
                      />
                    </View>
                  </View>
                );
              }
            })}

            <View
              style={{ flexDirection: "row", justifyContent: "space-between" }}
            >
              <TouchableOpacity
                onPress={() => {
                  setContents([...contents, { type: 0, content: "" }]);
                }}
              >
                <View style={styles.deleteOption}>
                  <View>
                    <AntDesign name="pluscircle" size={18} color="#41C3EE" />
                  </View>
                  <Text style={styles.addOptionText}>添加副标题</Text>
                </View>
              </TouchableOpacity>

              <TouchableOpacity
                onPress={() => {
                  setContents([...contents, { type: 1, content: "" }]);
                }}
              >
                <View style={styles.deleteOption}>
                  <View>
                    <AntDesign name="pluscircle" size={18} color="#41C3EE" />
                  </View>
                  <Text style={styles.addOptionText}>添加段落</Text>
                </View>
              </TouchableOpacity>
              <TouchableOpacity
                onPress={() => {
                  setIsVisible(true);
                }}
              >
                <View style={styles.deleteOption}>
                  <View>
                    <AntDesign name="pluscircle" size={18} color="#41C3EE" />
                  </View>
                  <Text style={styles.addOptionText}>添加图片</Text>
                </View>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </ScrollView>
      {!keyboardIsOpen && (
        <View style={styles.btnBox}>
          <TouchableOpacity style={styles.backBtn} onPress={() => onPreview()}>
            <Text style={{ color: "#41C3EE", fontSize: 16 }}>预览</Text>
          </TouchableOpacity>

          <TouchableOpacity
            style={styles.submitBtn}
            onPress={() => onConfirm()}
          >
            <Text style={{ color: "#fff", fontSize: 16 }}>确认</Text>
          </TouchableOpacity>
        </View>
      )}
      <Modal animationType="fade" transparent={true} visible={isVisible}>
        <View style={styles.ModalBackground}></View>
        <TouchableWithoutFeedback
          onPress={() => {
            setIsVisible(false);
          }}
        >
          <View style={styles.ModalTop}></View>
        </TouchableWithoutFeedback>
        <View style={styles.ModalStyle}>
          <TouchableOpacity
            style={styles.modalOption}
            onPress={() => {
              openCamera();
            }}
          >
            <Text style={styles.modalText}>拍摄</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={[styles.modalOption, { borderBottomWidth: 4 }]}
            onPress={() => pickImage()}
          >
            <Text style={styles.modalText}>从相册选择</Text>
          </TouchableOpacity>

          <TouchableOpacity
            style={styles.modalOption}
            onPress={() => {
              setIsVisible(false);
            }}
          >
            <Text style={styles.modalText}>取消</Text>
          </TouchableOpacity>
        </View>
      </Modal>
    </View>
  );
};

var styles = StyleSheet.create({
  container: {
    flex: 1,

    backgroundColor: "white",
    // padding: 16,
  },
  top: {
    borderBottomColor: "#eee",
    borderBottomWidth: 10,
    padding: 16,
  },
  title: {
    flexDirection: "row",
    marginBottom: 10,
  },
  titleIcon: { color: "red", fontSize: 16 },
  titleText: { color: "#aaa", fontSize: 16 },
  inputBox: {
    borderColor: "#ddd",
    borderWidth: 1,

    borderRadius: 2,
    padding: 10,
  },
  inputLine: {
    borderBottomColor: "#ddd",
    borderBottomWidth: 1,

    padding: 10,
  },
  context: {
    padding: 16,
    borderBottomColor: "#eee",
    borderBottomWidth: 10,
  },
  deleteOption: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    marginBottom: 15,
  },

  addOptionText: {
    color: "#41C3EE",
    paddingLeft: 10,
    fontSize: 16,
  },
  btnBox: {
    flexDirection: "row",
    justifyContent: "space-between",
    padding: 16,
  },
  backBtn: {
    borderWidth: 1,
    borderColor: "#41C3EE",
    alignItems: "center",
    padding: 10,
    borderRadius: 5,
    flex: 1,
    marginRight: 20,
    // width: 100,
  },
  submitBtn: {
    backgroundColor: "#41C3EE",
    alignItems: "center",
    padding: 10,
    borderRadius: 5,
    flex: 2,
    // width: 200,
  },
  ModalBackground: {
    backgroundColor: "#727272",
    opacity: 0.3,
    zIndex: 0,
    position: "absolute",
    width: "100%",
    height: "100%",
  },
  ModalStyle: {
    borderTopLeftRadius: 10,
    borderTopRightRadius: 10,
    backgroundColor: "#ffffff",
    zIndex: 1,
    position: "relative",
  },
  ModalTop: {
    flex: 1,
  },
  modalOption: {
    // backgroundColor: "yellow",
    width: "100%",
    padding: 15,
    borderBottomWidth: 0.5,
    borderBottomColor: "#e6e6e6",
  },
  modalText: {
    alignSelf: "center",
    fontSize: 16,
    color: "#201D1D",
  },
});

export default AddArticle;
